package system

import (
	"errors"
	"mytest/initialize/database"
	"mytest/models"
	"mytest/models/request"
	"mytest/until"

	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

func CheckLogin(req request.Login) (*models.SysUser, error) {
	if req.Password == "" {
		return nil, errors.New("密码不能为空")
	}
	if req.Username == "" {
		return nil, errors.New("用户名不能为空")

	}
	var user models.SysUser
	req.Password = until.Md5([]byte(req.Password))
	err := database.GetDB().Model(&models.SysUser{}).Where("username=? and password =?", req.Username, req.Password).
		First(&user).Error
	return &user, err
}
func RegisterLogin(user models.SysUser) (*models.SysUser, error) {
	err := database.GetDB().Where("username=? ", user.Username).First(&user).Error
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("用户名已注册")
	}
	//简单md5 加密一下
	user.Password = until.Md5([]byte(user.Password))
	user.UUID = uuid.NewV4()
	err = database.GetDB().Model(&user).Create(&user).Error
	return &user, err
}

//查找密码，修改
func SetPassword(db *gorm.DB, req request.ChangePassword) error {
	var user models.SysUser
	db = db.Model(&models.SysUser{}).Where("username=? and password =?", req.Username, until.Md5([]byte(req.Password))).First(&user)
	if errors.Is(db.Error, gorm.ErrRecordNotFound) {
		return errors.New("用户名或者密码错误")
	}
	return db.Update("password", until.Md5([]byte(req.NewPassword))).Error
}
func DeleteUser(db *gorm.DB, id uint) error {
	user := models.SysUser{ID: id}
	db = db.Delete(&user)
	if db.RowsAffected == 0 {
		return errors.New("用户ID错误")
	}
	return db.Error
}
func SetUserAuth(db *gorm.DB, req models.SysUser) error {
	return db.Model(req).Update("authority_id", req.AuthorityId).Error
}
func GetUserList(db *gorm.DB, req request.UserList) (error, interface{}, int64) {
	db = db.Model(&models.SysUser{})
	var out []models.SysUser
	if req.UserName != "" {
		db = db.Where("username like ?", until.Fuzzy(req.UserName))
	}
	var count int64
	err := db.Count(&count).Error
	if err != nil {
		return err, nil, 0
	}

	if req.Desc {
		err = db.Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Order(req.OrderKey).Find(&out).Error
		if err != nil {
			return err, nil, 0
		}
	} else {
		err = db.Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Find(&out).Error
		if err != nil {
			return err, nil, 0
		}
	}
	return nil, out, count
}
